<template>
  <EsDialog v-model="dialogVisible" :hiddenConfirm="true" close-name="关闭" :title="title" @open="handlerOpen"
            @close="resetState">
    <div class="border-bottom">
      <el-button type="primary" @click="formatSQL">{{ $t('selfAnalysis.DeveloperOptionDialog.format') }}</el-button>
    </div>
    <div class="ace-main">
      <!-- :value="selectSQL" -->
      <AceEditor ref="ace" :value="props.option" disabled v-bind="$attrs"/>
    </div>
  </EsDialog>
</template>

<script setup lang="ts">
import {ref, reactive, toRefs, computed, onMounted, watch, nextTick} from 'vue'
import EsDialog from '@/components/es-dialog/index.vue'
import {ElForm, ElMessage, ElMessageBox} from "element-plus/es";
import {useI18n} from 'vue-i18n'
import {loadAsyncComponent} from "@/utils";
import js_beautify from "@/js/table/beautify.js";

const {t} = useI18n()
const AceEditor = loadAsyncComponent(() => import('@/components/custom-ace.vue'))
const ace: any = ref("");

const props = defineProps({
  dialogVisible: {
    type: Boolean,
    required: true,
    default: true
  },
  option: {
    type: Object,
    default: () => {
      return {}
    }
  },
})

const {dialogVisible, option} = toRefs(props)

const emit = defineEmits(['update:dialogVisible'])
//表单元素
const ruleFormRef = ref(ElForm)
const State = () => {
  return {
    //弹框标题
    title: '详情',
    //实体详情
    detail: {} as any,
  }
}

const state = reactive(State())
const {title, detail} = toRefs(state)


//关闭弹框
const resetState = () => {
  emit('update:dialogVisible', false)
  Object.assign(state, State())
}

const handlerOpen = () => {
  console.log(ace)
  nextTick(() => {
    // ace.value.aceEditor.setValue(props.option.customStr);
    formatSQL()
  })
}


/*
* 格式化
* */
const formatSQL = () => {
  let sql: any = ace.value;
  let sqlOrig = sql.aceEditor?.getValue();
  if (sqlOrig) {
    formatterJson(sqlOrig);
    // let sqlFormatted = sqlFormatter.format(sqlOrig, {
    //     denseOperators: true,
    // });
    // let reg = /`([^s]*)`/;
    // let result = null;
    // result = reg.exec(sqlFormatted);
    // if (result != undefined && result.length > 0) {
    //     for (var i = 0; i < result.length; i++) {
    //         var resultNoBlank = result[i].replace(/^\s+|\s+$/g, "");
    //         sqlFormatted = sqlFormatted.replaceAll(result[i], resultNoBlank);
    //     }
    // }
    // sql.aceEditor.setValue(sqlFormatted);
  }
};

const formatterJson = (value: any) => {
  let sql: any = ace.value;
  sql.aceEditor.setValue(js_beautify(value, {}));
}
</script>

<style scoped lang="scss">
.ace-main {
  margin-top: 10px;
  // height: 90%;
  height: 400px;
}
</style>

